﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Mvc;
namespace Super.Common
{
    public class HttpHelper
    {

        /// <summary>
        /// 传说中 小巧的post提交
        /// </summary>
        /// <param name="postUrl"></param>
        /// <param name="paramData"></param>
        /// <returns></returns>
        public string PostWebRequest(string postUrl, string paramData)
        {
            string ret = string.Empty;
            try
            {
                ServicePointManager.Expect100Continue = false;//防止407 错误
                Encoding dataEncode = Encoding.GetEncoding("GBK");
                byte[] byteArray = dataEncode.GetBytes(paramData); //转化

                var webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
                webReq.Method = "POST";
                webReq.ContentType = "application/x-www-form-urlencoded";
                webReq.ContentLength = byteArray.Length;

                Stream newStream = webReq.GetRequestStream();
                newStream.Write(byteArray, 0, byteArray.Length);//写入参数
                newStream.Close();
                var response = (HttpWebResponse)webReq.GetResponse();
                var sr = new StreamReader(response.GetResponseStream(), Encoding.Default);
                ret = sr.ReadToEnd();
                sr.Close();
                response.Close();
                newStream.Close();
            }
            catch (Exception ex)
            {
                //todo:bq 写入日志
            }
            return ret;
        }


        public static string GetWebRequest(string url)
        {
            var result = "";

            var httpWebRequest = WebRequest.Create(url) as HttpWebRequest;


            if (httpWebRequest == null) { return result; }
            //不加头信息的话有些网页会限制，比如alibaba的产品列表页面
            httpWebRequest.Method = "GET";
            httpWebRequest.KeepAlive = true;
            httpWebRequest.Timeout = 20000;
            httpWebRequest.ContentType = "text/html";//application/x-www-form-urlencoded
            httpWebRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:14.0) Gecko/20100101 Firefox/14.0.1";


            var httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
            if (httpWebResponse == null) { return result; }

            var stream = httpWebResponse.GetResponseStream();

            if (stream == null) { return result; }

            var reader = new StreamReader(stream, Encoding.Default);
            result = reader.ReadToEnd();
            reader.Close();
            stream.Close();
            httpWebResponse.Close();
            return result;
        }



        public static string SaveImage(string url, string path)
        {
            // 初始化一大堆变量
            const string attachdir = "/upload"; // 上传文件保存路径，结尾不要带/
            const int dirtype = 1; // 1:按天存入目录 2:按月存入目录 3:按扩展名存目录  建议使用按天存
            const int maxattachsize = 1048576; // 最大上传大小，默认是2M
            const string imageType = "jpg,jpeg,gif,png";

            var mywebclient = new WebClient();
            string attachDir, attachSubdir;
            // 取上载文件后缀名
            string extension = url.Substring(url.LastIndexOf('.') + 1).ToLower();

            switch (dirtype)
            {
                case 2:
                    attachSubdir = "month_" + DateTime.Now.ToString("yyMM");
                    break;
                case 3:
                    attachSubdir = "ext_" + extension;
                    break;
                default:
                    attachSubdir = "day_" + DateTime.Now.ToString("yyMMdd");
                    break;
            }
            attachDir = path + "/" + attachSubdir + "/";
            string filename = url.Substring(url.LastIndexOf('/') + 1).ToLower();
            string filepath = attachDir + "/" + filename;
            CreateFolder(attachDir);
            try
            {
                mywebclient.DownloadFile(url, filepath);
                return attachdir+"/image/"+ attachSubdir + "/" + filename;
            }
            catch (Exception ex)
            {
                return "error";
            }
        }

        /// <summary>
        /// 创建文件夹
        /// </summary>
        /// <param name="folderPath"></param>
        private static void CreateFolder(string folderPath)
        {
            if (!System.IO.Directory.Exists(folderPath)) System.IO.Directory.CreateDirectory(folderPath);
        }

    }
}
